package br.com.knowledge.helper;

import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.hibernate.classic.Session;
import br.com.knowledge.persistence.hibernate.dao.CadProjetoDAO;
import com.opensymphony.xwork2.ActionSupport;

public class ConsisteExclusao extends ActionSupport implements SessionAware{

	public void setSession(Map<String, Object> arg0) {		
	}

	private String comando;
	String[] nulos = {"\\[", "\\]"};

	public boolean consisteExclusaoDado( String tabela, String coluna, Integer id){

		comando = "SELECT   'select count(1) from ' || cl.relname || ' where ' || a.attname || '= " + Integer.toString(id) +  "' ";
		comando = comando + " FROM pg_catalog.pg_attribute a ";
		comando = comando + " JOIN pg_catalog.pg_class cl ON (a.attrelid = cl.oid AND cl.relkind = 'r') ";
		comando = comando + " JOIN pg_catalog.pg_namespace n ON (n.oid = cl.relnamespace) ";
		comando = comando + " JOIN pg_catalog.pg_constraint ct ON (a.attrelid = ct.conrelid AND";
		comando = comando + " ct.confrelid != 0 AND ct.conkey[1] = a.attnum)";
		comando = comando + " JOIN pg_catalog.pg_class clf ON (ct.confrelid = clf.oid AND clf.relkind = 'r')";
		comando = comando + " JOIN pg_catalog.pg_namespace nf ON (nf.oid = clf.relnamespace)";
		comando = comando + " JOIN pg_catalog.pg_attribute af ON (af.attrelid = ct.confrelid AND";
		comando = comando + " af.attnum = ct.confkey[1])";
		comando = comando + " AND clf.relname = '" + tabela + "' And af.attname = '" + coluna + "'";

		CadProjetoDAO gDao = new CadProjetoDAO();

		Session sessionDao = (Session) gDao.getSession();

		sessionDao.getTransaction().begin();

		try{
			List<Object> comandosDeletar = (List<Object>) sessionDao.createSQLQuery(comando).list();
			//sessionDao.cancelQuery();
			if(comandosDeletar.size()>-1){
				for( Object executarComando : comandosDeletar){

					Object temp = (Object) sessionDao.createSQLQuery((String) executarComando).list();
					String valor = temp.toString();  

					for (String n:nulos){  
						valor = valor.replaceAll(n, "");   					
					}
					int i = Integer.parseInt(valor);  
					if(i > 0){
						return false;
					}
				}
			}

		}catch (Exception ex) {
			sessionDao.getTransaction().rollback();
		}finally{
			sessionDao.close();
		}
		return true;
	}
}
